#include "gl_hershey.h"

#include <cstring>
#include <cstdarg>
#include <cstdio>
#include <gl\glfw.h>
#include <math.h>
#include "simplexFont.h"

HersheyText* HersheyText::_instance = 0x0;

HersheyText* HersheyText::Instance()
{ 
	if( !_instance )
	{
		_instance = new HersheyText();
	}

	return _instance;
}

void HersheyText::moveTo(float x, float y)
{
    moveToX = x;
    moveToY = y;
}

void HersheyText::centerText( float x, float y )
{
	moveTo( x + textW, y + textH  );
}



void HersheyText::lineTo(float x, float y)
{	
    glBegin(GL_LINES);
        glVertex2f( moveToX , moveToY );
        glVertex2f( x,y);
    glEnd();
    moveToX = x;
    moveToY = y;
}

void HersheyText::drawChar(int c,float scale){
   int verts = (int)simplex[c][0];
   //float spacing = simplex[c][1];
   
   float ax = simplex[c][2];
   float ay = simplex[c][3]; 
   moveTo( (tx+ax*scale-scale*2.0f), ceil(ty-ay*scale+scale*2.0f) );  
   int i=0;
	 for(i=4; i<verts*2; i+=2)
   {
      ax = simplex[c][i+0];
      ay = simplex[c][i+1];

      if(ax==-1 || ay == -1) moveTo(tx+simplex[c][i+2]*scale-scale*2.0f, ceil(ty-simplex[c][i+3]*scale+scale*2.0f) );
      else lineTo( (tx+ax*scale-scale*2.0f), ceil(ty-ay*scale+scale*2.0f) );        
   }
	 lineTo( (tx+simplex[c][i+0]*scale-scale*2.0f) , ceil( ty-simplex[c][i+1]*scale+scale*2.0f ) );
}


void HersheyText::setFont(float w, float h)
{
	textW = w/20; textH = h/20;
}

void HersheyText::glPrintf(const char *format,...)
{
    if (format == NULL) return;
    float sx = moveToX;
    //float sy = moveToY;
    tx=moveToX;
    ty=moveToY;

    char finalText[256];

    va_list args;
    va_start(args, format);
    vsprintf(finalText, format, args);
		//vsprintf_s( str, siz, format, ap );
		//vsprintf_s(finalText,256,format,args);
    va_end(args);

    int len;
    int i;
            len = (int) strlen(finalText);
            for (i = 0; i < len; i++) {
                    if( finalText[i] == '\n' )
                    {
                            tx = sx;
                            ty += 40*textH;
                    }else{
                            int c = (int)finalText[i]-32;
                            if(c < 0 || c > 94) return;
                            {
                                    drawChar( c, textW );
                                    tx += simplex[c][1]*textW;
                            }
                    }
            }
    moveToX = sx;
    moveToY = ty;

}

